import mime from 'mime'
export async function fileType(file) {
  const buffers = await readBuffer(file, 0, 8)
  const uint8Array = new Uint8Array(buffers)
  return parse(file, uint8Array)
}

function readBuffer(file, start = 0, end = 2) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      resolve(reader.result)
    }
    reader.onerror = reject
    reader.readAsArrayBuffer(file.slice(start, end))
  })
}
function initCheck(buffer) {
  return (headers, options) => {
    options = {
      offset: 0,
      ...options
    }
    for (const [index, header] of headers.entries()) {
      // If a bitmask is set
      if (options.mask) {
        // If header doesn't equal `buf` with bits masked off
        if (header !== (options.mask[index] & buffer[index + options.offset])) {
          return false
        }
      } else if (header !== buffer[index + options.offset]) {
        return false
      }
    }

    return true
  }
}

function parse(file, buffer) {
  const check = initCheck(buffer)
  if (check([0x42, 0x4d])) {
    return {
      ext: 'bmp',
      mime: 'image/bmp'
    }
  }
  if (check([0x0b, 0x77])) {
    return {
      ext: 'ac3',
      mime: 'audio/vnd.dolby.dd-raw'
    }
  }
  if (check([0x78, 0x01])) {
    return {
      ext: 'dmg',
      mime: 'application/x-apple-diskimage'
    }
  }
  if (check([0x4d, 0x5a])) {
    return {
      ext: 'exe',
      mime: 'application/x-msdownload'
    }
  }
  if (check([0x1f, 0xa0]) || check([0x1f, 0x9d])) {
    return {
      ext: 'Z',
      mime: 'application/x-compress'
    }
  }
  if (check([0x47, 0x49, 0x46])) {
    return {
      ext: 'gif',
      mime: 'image/gif'
    }
  }
  if (check([0xff, 0xd8, 0xff])) {
    return {
      ext: 'jpg',
      mime: 'image/jpeg'
    }
  }
  if (check([0x49, 0x49, 0xbc])) {
    return {
      ext: 'jxr',
      mime: 'image/vnd.ms-photo'
    }
  }
  if (check([0x1f, 0x8b, 0x8])) {
    return {
      ext: 'gz',
      mime: 'application/gzip'
    }
  }

  if (check([0x42, 0x5a, 0x68])) {
    return {
      ext: 'bz2',
      mime: 'application/x-bzip2'
    }
  }
  if (check([0x50, 0x4b, 0x3, 0x4])) {
    return {
      ext: mime.getExtension(file.type),
      mime: file.type
    }
  }
  if (check([0x12, 0x34, 0x56, 0x78, 0x90, 0xff])) {
    return {
      ext: mime.getExtension(file.type),
      mime: file.type
    }
  }
  if (check([0x31, 0xbe, 0x00, 0x00, 0x00, 0xab, 0x00, 0x00])) {
    return {
      ext: mime.getExtension(file.type),
      mime: file.type
    }
  }
  if (check([0x7f, 0xfe, 0x34, 0x0a])) {
    return {
      ext: mime.getExtension(file.type),
      mime: file.type
    }
  }
  if (check([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])) {
    return {
      ext: mime.getExtension(file.type),
      mime: file.type
    }
  }
  if (check([0x25, 0x50, 0x44])) {
    return {
      ext: mime.getExtension(file.type),
      mime: file.type
    }
  }
  console.log(file)
}
